<template>
  <div ref="iframeBoxRef" class="width-100" v-resize="adjustIframe">
    <iframe
      v-if="modelValue"
      ref="iframeEl"
      class="width-100"
      frameborder="0"
      :srcdoc="getPreviewHtml(modelValue)"
      @load="adjustIframe()"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import path from 'path-browserify';

// -------------------------- 页面参数 --------------------------
defineProps<{
  modelValue: string;
}>();

const $emits = defineEmits<{
  'click': [],
  'dblclick': [],
}>();

const iframeBoxRef = ref<HTMLDivElement>();

const iframeEl = ref<HTMLIFrameElement>();

// -------------------------- 页面数据 --------------------------
const baseUrl = import.meta.env.BASE_URL;

function getPreviewHtml(htmlStr: string) {
  var headHtml = `<base href="${baseUrl}">`;
  [
    '/tinymce/skins/ui/oxide' + "/content.min.css",
    '/tinymce/skins/content/default/content.min.css' + "",
  ].forEach((url: string) => {
    headHtml += `<link type="text/css" rel="stylesheet" href="${path.join(baseUrl, url)}" crossorigin="anonymous">`;
  });
  headHtml += `<style type="text/css">
  html { width: fit-content; overflow-y: hidden; min-width: 100%; }
  body { margin: 0; }
  p { margin: 0; }
  ul,ol { margin: 0; padding: 0; }
  ol { padding-left: 14px; }
  ul { padding-left: 17px; }
  pre { margin: 0; padding: 0; }
<\/style>`;

    return `<!DOCTYPE html>
<html>
  <head>${headHtml}</head>
  <body class="mce-content-body">
    ${htmlStr}
  </body>
</html>`
}

function adjustIframe() {
  var ifm = iframeEl.value;
  if (ifm) {
    const documentElement = ifm.contentWindow.document.documentElement;
    if (documentElement) {
      ifm.height = documentElement.offsetHeight + '';
      documentElement.onclick = function(event) {
        const target = event.target as HTMLAnchorElement;
        if (target.tagName === "A") {
          event.preventDefault();
          window.open(target.href, "_blank");
        } else {
          $emits('click');
        }
      };
      documentElement.ondblclick = () => {
        $emits('dblclick');
      };
    }
  }
}

</script>
